package com.itcast.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @param
 * @return
 */
@WebFilter(value="/*",initParams = {@WebInitParam(name = "encoding",value = "utf-8")})//解决所有请求和响应中的乱码
public class StudentFilter implements Filter {
    String encoding=null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
         encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //在此过滤器中设置字符集，一次性解决乱码问题
        req.setCharacterEncoding(encoding);
        resp.setContentType("text/html;charset="+encoding);
        //设置完成后放行
        chain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}
